package com.leetcodehot.problems;

import java.util.ArrayDeque;
import java.util.Deque;

public class problems116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        Deque<Node> deque = new ArrayDeque<Node>();
        if (root == null) return root;
        deque.addLast(root);
        while (!deque.isEmpty()) {
            int n = deque.size();
            Node pre = null;
            while (n-- > 0) {
                Node cur = deque.removeFirst();
                if (pre != null) {
                    pre.next = cur;
                }
                pre = cur;
                if (cur.left != null) deque.addLast(cur.left);
                if (cur.right != null) deque.addLast(cur.right);
            }
        }
        return root;
    }
}
